package org.monster.context.core;

import org.monster.context.reader.tag.FilterTag;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 过滤器上下文
 */
public class FilterContext {

    /**
     * 获取过滤器初始化
     *
     * @param filterImpl 过滤器实现
     * @return 过滤器模式
     */
    public FilterPattern getFilterInit(Class<?> filterImpl) {
        if (filterImpl.equals(FilterInitPattern.class)) {
            return new FilterInitPattern();
        } else if (filterImpl.equals(FilterNormalPattern.class)) {
            return new FilterNormalPattern();
        }
        return null;
    }

    /**
     * 执行
     *
     * @param loader          类加载器实现
     * @param filterConfigCache 过滤器配置映射
     * @param filterImpl      过滤器实现
     * @throws ClassNotFoundException 类未找到异常
     * @throws InstantiationException 实例化异常
     * @throws IllegalAccessException 非法访问异常
     */
    public void execute(ApplicationClassLoaderImpl loader,
                        FilterConfigCache filterConfigCache, Class<?> filterImpl)
            throws ClassNotFoundException, InstantiationException,
            IllegalAccessException {
        FilterPattern filter = getFilterInit(filterImpl);
        Map<String, List<FilterTag>> filterTags = filterConfigCache.getTags();
        Set<String> keySet = filterTags.keySet();
        for (String key : keySet) {
            loader.getWebClassLoader(key);
            List<FilterTag> fts = filterTags.get(key);
            for (FilterTag filterTag : fts) {
                Class<?> clazz;
                clazz = loader.loadClass(filterTag.getFilterClass());
                Class<?>[] interfaces = clazz.getInterfaces();
                for (Class<?> inf : interfaces) {
                    if (inf.getName().equals("javax.servlet.Filter")) {
                        filter.loadFilter(key, clazz, filterTag);
                    }
                }
            }
        }
    }
}
